import { App } from 'vue'
import { checkPermission } from '@/utils/utils'

function directivesPermission (el: any, binding: any) {
  const { value } = binding
  if (value && value instanceof Array) {
    const hasPermission = checkPermission(value)
    if (!hasPermission) {
      el.parentNode && el.parentNode.removeChild(el)
    }
  } else {
    throw new Error('binding is Array')
  }
}

export default {

  install (app: App) {
    /*
      校验权限，没有权限会删除dom节点
      @param [array] roles --权限名称
    */
    app.directive('permission', {
      mounted (el, binding) {
        directivesPermission(el, binding)
      },
      updated (el, binding) {
        directivesPermission(el, binding)
      }
    })
    /*
      防抖,单位时间内触发最后一次
      @param [function] fn --执行事件
      @param [?string] event = 'click' -- 事件类型
      @param [?number] wait = 300 -- 时间间隔
      @param [?boolean] boolean = true -- 事件冒泡-false , 事件捕获--true
      <el-button v-debounce="[test,'click',1000,false]">防抖</el-button>
    */
    app.directive('debounce', {
      mounted (el, binding) {
        const [fn, event = 'click', wait = 300, immediate = true] = binding.value
        let timer: any = null
        el.addEventListener(event, () => {
          timer && clearTimeout(timer)
          timer = setTimeout(() => fn(), wait)
        }, immediate)
      }
    })
    /*
      节流 每单位时间可触发一次
      第一次瞬间触发，最后一次不管是否达到间隔时间依然触发
      @param {Function} fn - 执行事件
      @param {?Number} time = 300 - 间隔时间
      @param {?String} event = 'click' - 事件类型 例："click"
      例：<el-button v-throttle="[reset,`click`,300]">刷新</el-button>
      传递参数则：<el-button v-throttle="[()=>reset(param),`click`,300]">刷新</el-button>
    */
    app.directive('throttle', {
      mounted (el, binding) {
        const [fn, event = 'click', time = 300] = binding.value
        let timer: any
        let timerEnd: any
        el.addEventListener(event, () => {
          if (timer) {
            clearTimeout(timerEnd)
            return (timerEnd = setTimeout(() => fn(), time))
          }
          fn()
          timer = setTimeout(() => (timer = null), time)
        })
      }
    })
    // v-dialogDrag: 弹窗拖拽
    app.directive('dialogDrag', {
      updated (el) {
        const dragDom = el.querySelector('.el-dialog')
        dragDom.style.top = 0
        dragDom.style.left = 0
      },
      mounted (el) {
        const dialogHeaderEl = el.querySelector('.el-dialog__header')
        const dragDom = el.querySelector('.el-dialog')
        dialogHeaderEl.style.cursor = 'move'

        // 获取原有属性 ie dom元素.currentStyle 火狐谷歌 window.getComputedStyle(dom元素, null);
        const sty = dragDom.currentStyle || window.getComputedStyle(dragDom, null)

        dialogHeaderEl.onmousedown = (e: MouseEvent) => {
          // 鼠标按下，计算当前元素距离可视区的距离
          const disX = e.clientX - dialogHeaderEl.offsetLeft
          const disY = e.clientY - dialogHeaderEl.offsetTop
          const screenWidth = document.body.clientWidth // body当前宽度
          const screenHeight = document.documentElement.clientHeight // 可见区域高度(应为body高度，可某些环境下无法获取)
          const dragDomWidth = dragDom.offsetWidth // 对话框宽度
          const dragDomheight = dragDom.offsetHeight // 对话框高度
          const minDragDomLeft = dragDom.offsetLeft
          const maxDragDomLeft = screenWidth - dragDom.offsetLeft - dragDomWidth
          const minDragDomTop = dragDom.offsetTop
          const maxDragDomTop = screenHeight - dragDom.offsetTop - dragDomheight

          // 获取到的值带px 正则匹配替换
          let styL: any, styT: any

          // 注意在ie中 第一次获取到的值为组件自带50% 移动之后赋值为px
          if (sty.left.includes('%')) {
            styL = +document.body.clientWidth * (+sty.left.replace(/%/g, '') / 100)
            styT = +document.body.clientHeight * (+sty.top.replace(/%/g, '') / 100)
          } else {
            styL = +sty.left.replace(/\px/g, '')
            styT = +sty.top.replace(/\px/g, '')
          }

          document.onmousemove = function (e: MouseEvent) {
            // 通过事件委托，计算移动的距离
            let l = e.clientX - disX
            let t = e.clientY - disY

            // 边界处理
            if (-l > minDragDomLeft) {
              l = -minDragDomLeft
            } else if (l > maxDragDomLeft) {
              l = maxDragDomLeft
            }
            if (-t > minDragDomTop) {
              t = -minDragDomTop
            } else if (t > maxDragDomTop) {
              t = maxDragDomTop
            }
            // 移动当前元素
            dragDom.style.left = `${l + styL}px`
            dragDom.style.top = `${t + styT}px`

            // 将此时的位置传出去
            // binding.value({x:e.pageX,y:e.pageY})
          }

          document.onmouseup = function () {
            document.onmousemove = null
            document.onmouseup = null
          }
        }
      }
    })
  }
}
